//
//  RemindViewController.m
//  SmartCup
//
//  Created by Kendama on 2017/5/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "RemindViewController.h"
#import "RemindTableViewCell.h"
#import "DTCLocalPushManager.h"

@interface RemindViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;

@property(nonatomic, strong) NSArray *remindList;

/** 背景图 **/
@property(nonatomic,strong) UIImageView *backbroundView;
@property(nonatomic,strong) UILabel *tipsLabel;
@property(nonatomic,strong) UIView *noMachineView;

@end

@implementation RemindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)refreshBaseControlValue
{
    [self setNavigationTitle:@"我的水杯" titleColor:[UIColor whiteColor]];
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"3E76F6"];
    [self setRightButtonImage:[UIImage imageNamed:@"icon_add"]];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(64);
        make.width.equalTo(self.view);
        make.bottom.mas_equalTo(self.view.mas_bottom);
    }];
    
    self.remindList = [RemindModel selectAllObject];
    
    [self masLayout];
    
    [self checkData];
    
}

- (void)checkData {
    if (self.remindList.count == 0) {
        [self.view bringSubviewToFront:self.noMachineView];
    } else {
        [self.view bringSubviewToFront:self.tableView];
    }
}

#pragma mark -- 事件
- (void)onRightButtonClick:(id)sender
{
    self.hidesBottomBarWhenPushed = YES;
    RemindSettingViewController *vc = [[RemindSettingViewController alloc] init];
    vc.type = 1;
    vc.updateBlock = ^{
        self.remindList = [RemindModel selectAllObject];
        [self.tableView reloadData];
        [self checkData];
        
        [self sendNotification];
    };
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;

}

- (void) sendNotification{
    [[DTCLocalPushManager defalutService] removeAllLocalNotification];
    NSArray *data = [RemindModel selectAllObject];
    for (RemindModel *remind in data) {
        if (remind.switchMark) {
            NSInteger count = remind.count;
            NSInteger startSP = [self getYearMouthDayWithTime:remind.startTime];
            NSInteger endSP = [self getYearMouthDayWithTime:remind.endTime];
            NSInteger equal = [self calculateAverageWithCount:count andTimeSp:startSP andTimeSp2:endSP];
            NSInteger nowSP = [[NSDate date] timeIntervalSince1970];
            
            if (count == 0) { // 自动模式
                NSInteger month = [[self getMonth] intValue];
                if (3 <= month && month <= 5) { // 春季
                    count = [self calculateCountWithMinute:75 andStartTime:startSP andEndTime:endSP];
                    equal = 75*60;
                } else if (6 <= month && month <= 8) { // 夏季
                    count = [self calculateCountWithMinute:60 andStartTime:startSP andEndTime:endSP];
                    equal = 60*60;
                } else if (9 <= month && month <= 11) { // 秋季
                    count = [self calculateCountWithMinute:75 andStartTime:startSP andEndTime:endSP];
                    equal = 75*60;
                } else { // 冬季
                    count = [self calculateCountWithMinute:90 andStartTime:startSP andEndTime:endSP];
                    equal = 90*60;
                }

            }

            for (int j = 0; j < 30; j++) {
                for (int i = 1; i <= count; i++) {
                    NSString *sound = [NSString string];
                    if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
                        sound = @"sound.caf";
                    } else {
                        sound = @"silent.caf";
                    }
                    NSLog(@"自动模式：%li",startSP + equal*i + 60*60*24*j);
                    NSInteger notificationSp = startSP + equal*i + 60*60*24*j;
                    if (notificationSp > nowSP) {
                        NSDate *date = [NSDate dateWithTimeIntervalSince1970:notificationSp];
                        [[DTCLocalPushManager defalutService]addLocalNotificationByBody:[NSString stringWithFormat:@"一杯子提醒您该%@啦",remind.type] sound:sound date:date userInfo:@{@"remind":remind.type} repeat:NO];
                    }

                }

            }
        }
    }

}

//- (void) sendNotification{
//    [[DTCLocalPushManager defalutService] removeAllLocalNotification];
//    NSArray *data = DTCEXRACT_OBJECT(@"remind");
//    for (NSDictionary *dict in data) {
//        if ([dict[@"switch"] isEqualToString:@"YES"]) {
//            NSLog(@"开始时间：%li",(long)[self getYearMouthDayWithTime:dict[@"startTime"]]);
//            NSInteger count = [dict[@"count"] intValue];
//            NSInteger startSP = [self getYearMouthDayWithTime:dict[@"startTime"]];
//            NSInteger endSP = [self getYearMouthDayWithTime:dict[@"endTime"]];
//            NSInteger equal = [self calculateAverageWithCount:count andTimeSp:startSP andTimeSp2:endSP];
//            NSInteger nowSP = [[NSDate date] timeIntervalSince1970];
//
//            if (count == 0) { // 自动模式
//                NSInteger month = [[self getMonth] intValue];
//                if (3 <= month && month <= 5) { // 春季
//                    count = [self calculateCountWithMinute:75 andStartTime:startSP andEndTime:endSP];
//                    equal = 75*60;
//                } else if (6 <= month && month <= 8) { // 夏季
//                    count = [self calculateCountWithMinute:60 andStartTime:startSP andEndTime:endSP];
//                    equal = 60*60;
//                } else if (9 <= month && month <= 11) { // 秋季
//                    count = [self calculateCountWithMinute:75 andStartTime:startSP andEndTime:endSP];
//                    equal = 75*60;
//                } else { // 冬季
//                    count = [self calculateCountWithMinute:90 andStartTime:startSP andEndTime:endSP];
//                    equal = 90*60;
//                }
//                
//            }
//
//            for (int j = 0; j < 30; j++) {
//                for (int i = 1; i <= count; i++) {
//                    //                    NSLog(@"提示：%li",startSP + equal*i + 60*60*24*j);
//                    NSString *sound = [NSString string];
//                    if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
//                        sound = @"sound.caf";
//                    } else {
//                        sound = @"silent.caf";
//                    }
//                    NSLog(@"自动模式：%li",startSP + equal*i + 60*60*24*j);
//                    NSInteger notificationSp = startSP + equal*i + 60*60*24*j;
//                    if (notificationSp > nowSP) {
//                        NSDate *date = [NSDate dateWithTimeIntervalSince1970:notificationSp];
//                        [[DTCLocalPushManager defalutService]addLocalNotificationByBody:@"一杯子提醒您该喝水啦" sound:sound date:date userInfo:@{@"remind":@"water"} repeat:NO];
//                    }
//
//                }
//
//            }
//        }
//    }
//}

- (NSInteger)calculateCountWithMinute:(NSInteger)minute andStartTime:(NSInteger)startTime andEndTime:(NSInteger)endTime {
    NSInteger count;
    count = (endTime - startTime)/60/minute;
    
    if (count < 1) {
        return 1;
    }
    return count;
}

// 获取当前月份
- (NSString *)getMonth
{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM"];
    NSString *monthString = [dateFormatter stringFromDate:date];
    monthString = [monthString substringToIndex:2];
    return monthString;
}

- (NSInteger)calculateAverageWithCount:(NSInteger)count andTimeSp:(NSInteger)timeSp andTimeSp2:(NSInteger)timeSp2{
    NSInteger different = timeSp2 - timeSp;
    NSInteger equal = different/(count+1);
    return equal;
}

// 将某个时间点转换成时间戳
- (NSInteger)getYearMouthDayWithTime:(NSString *)time {
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *formatTime = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate:date],time];
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date2 = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date2 timeIntervalSince1970]] integerValue];
    return timeSp;
}

#pragma mark -- 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.remindList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return px1920Height(400);
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RemindTableViewCell *cell = [RemindTableViewCell cellWithTableView:tableView];
    RemindModel *remind = self.remindList[indexPath.row];
    cell.remind = remind;
    cell.switchBlock = ^(BOOL switchMark){
        remind.switchMark = switchMark;
        [remind updateObject];
        [self.tableView reloadData];
        [self sendNotification];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.hidesBottomBarWhenPushed = YES;
    RemindSettingViewController *vc = [[RemindSettingViewController alloc] init];
    RemindModel *remind = self.remindList[indexPath.row];
    vc.remindModel = remind;
    vc.updateBlock = ^{
        self.remindList = [RemindModel selectAllObject];
        [self.tableView reloadData];
        [self checkData];
        [self sendNotification];
    };
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}


- (void) masLayout{
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(64);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(-49);
    }];
    
    [self.noMachineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.width.mas_equalTo(superView);
        make.bottom.mas_equalTo(superView.mas_bottom);
    }];
    
    [self.backbroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(px1920Height(272));
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.width.mas_equalTo(px1080Width(456));
        make.height.mas_equalTo(px1920Height(456));
    }];
    
    [self.tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.backbroundView.mas_bottom).with.offset(px1920Height(40));
        make.width.mas_equalTo(superView);
        make.height.mas_equalTo(px1920Height(73));
    }];
}



#pragma mark -- 懒加载
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [superView addSubview:_tableView];
    }
    return _tableView;
}



- (UILabel *)tipsLabel
{
    if(!_tipsLabel)
    {
        UIView *superView = self.noMachineView;
        _tipsLabel = [[UILabel alloc]init];
        [superView addSubview:_tipsLabel];
        [_tipsLabel setFont:[UIFont systemFontOfSize:px1080Width(52)]];
        [_tipsLabel setTextColor:[UIColor colorWithHexString:@"#585D6D"]];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.text = @"您好像还没设置喝水提醒";
    }
    return _tipsLabel;
}

- (UIImageView *)backbroundView
{
    if(!_backbroundView)
    {
        UIView *superView = self.noMachineView;
        _backbroundView = [[UIImageView alloc]init];
        [superView addSubview:_backbroundView];
        _backbroundView.image = [UIImage imageNamed:@"bg_equipment"];
    }
    return _backbroundView;
}

- (UIView *)noMachineView
{
    if(!_noMachineView)
    {
        UIView *superView = self.view;
        _noMachineView = [[UIView alloc]init];
        _noMachineView.backgroundColor = [UIColor whiteColor];
        [superView addSubview:_noMachineView];
    }
    return _noMachineView;
}

- (NSArray *)remindList
{
    if(!_remindList)
    {
        _remindList = [[NSArray alloc]init];
    }
    return _remindList;
}


@end
